import {Restivus} from 'meteor/nimble:restivus';
import {Meteor} from 'meteor/meteor';
import {Random} from 'meteor/random';
import R from 'ramda';
import {Families} from '../imports/api/families';
import {Gateways} from '../imports/api/gateways';
import {AnFangs} from '../imports/api/an_fangs';
import {HTTP} from 'meteor/http';
if (Meteor.isServer) {
    Meteor.startup(() => {
        let Api = new Restivus({
            useDefaultAuth: true,
            prettyJson: true,
        });
        // 获取登录用户的家庭信息
        Api.addRoute('getLoginFamily', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token": logintoken});
                        if (user) {
                            const families = Families.find({'createdUser._id': user._id}, {fields: {belongTo: 0, createdUser: 0 }}).fetch();
                            return {success: true, result: {families: families, error: ''}, resultCode: 1000};
                        } else {
                            return {success: false, result: {error: '请登录！'}, resultCode: 1004};
                        }
                    }
                    return {success: false, result: {error: '没有获取到信息！'}, resultCode: 1002};
                }
            }
        });
        // 获取登录用户的默认家庭信息及网关信息
        Api.addRoute('defaultFamily', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token": logintoken});
                        if (user) {
                            const families = Families.find({'createdUser._id': user._id}, {fields: {belongTo: 0, createdUser: 0 }}).fetch();
                            let family = {};
                            if (families.length > 1) {
                                family = Families.findOne({'createdUser._id': user._id, isDefault: true}, {fields: {belongTo: 0, createdUser: 0 }});
                                if (!family) {
                                    family = families[0];
                                }
                            } else {
                                family = families[0];
                            }

                            let gateway = {};
                            if(family){
                                const rms = family.rooms;
                                if(rms.length > 0) {
                                    const arr = R.filter((s) => {
                                            return s.isDef === true;
                                        })(rms) || [];
                                    family.rooms = arr;
                                }
                                const gateways = Gateways.find({'familyId': family._id}).fetch();
                                if (gateways.length > 1) {
                                    gateway = Gateways.findOne({familyId: family._id, isDefault: true});
                                    if (!gateway) {
                                        gateway = gateways[0];
                                    }
                                } else {
                                    gateway = gateways[0];
                                } 
                            }
                            return {success: true, result: {family: family, gateway: gateway, error: ''}, resultCode: 1000};
                        } else {
                            return {success: false, result: {error: '请登录！'}, resultCode: 1004};
                        }
                    }
                    return {success: false, result: {error: '没有获取到信息！'}, resultCode: 1002};
                }
            }
        });
        // 切换家庭
        Api.addRoute('getFamilyById', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const familyId = param._id;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token": logintoken});
                        if (user) {
                            let family = Families.findOne({'_id': familyId});
                            let gateway = {};
                            if (family) {
                                const gateways = Gateways.find({'familyId': family._id}, {fields: {belongTo: 0, createdUser: 0 }}).fetch();
                                if (gateways.length > 1) {
                                    gateway = Gateways.findOne({familyId: family._id, isDefault: true}, {fields: {belongTo: 0, createdUser: 0 }});
                                    if (!gateway) {
                                        gateway = gateways[0];
                                    }
                                } else {
                                    gateway = gateways[0];
                                }
                            } else {
                                family = {};
                                gateway = {};
                            }
                            return {success: true, result: {family: family, gateway: gateway, error: ''}, resultCode: 1000};
                        } else {
                            return {success: false, result: {error: '请登录！'}, resultCode: 1004};
                        }
                    }
                    return {success: false, result: {error: '没有获取到信息！'}, resultCode: 1002};
                }
            }
        });
        // 添加家庭信息
        Api.addRoute('addFamily', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const user = Meteor.users.findOne({
                            "services.resume.loginTokens.token": logintoken
                        });
                        if (user) {
                            delete param.token;
                            const arr = [];
                            arr.push({_id: user._id, name: user.username});
                            param['belongTo'] = arr;
                            param['createdUser'] = {_id: user._id, name: user.username};
                            param['isDefault'] = true;
                            param['rooms'] = [{'_id': Random.id(6), name: '默认房间', isDef: true}];
                            Families.update({'createdUser._id': user._id, isDefault: true}, {$set: {isDefault: false}},{multi: true});
                            const family = Families.insert(param);
                            if (family) {
                                const afs = AnFangs.find({familyId: family}).fetch();
                                afs.forEach((af) => {
                                    AnFangs.remove(af._id);
                                })
                                AnFangs.insert({name: '外出布防', familyId: family, status: false, devices: [], createdName: user.username});
                                AnFangs.insert({name: '在家布防', familyId: family, status: false, devices: [], createdName: user.username});
                                AnFangs.insert({name: '撤防', familyId: family, status: false, devices: [], createdName: user.username});
                                Meteor.users.update({_id: user._id}, {$addToSet: {familyIds: family}});
                                return {success: true, result: family, resultCode: 1000};
                            } else {
                                return {success: false, result: '家庭信息添加失败！', resultCode: 1004};
                            }
                        } else {
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有获取到登录用户的信息！', resultCode: 1002};
                }
            }
        });
        // 修改家庭信息
        Api.addRoute('editFamily', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const fId = param.familyId;
                        const name = param.name;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token": logintoken});
                        if (user) {
                            const family = Families.update({_id: fId}, {$set: {name: name}});
                            if (family) {
                                return {success: true, resultCode: 1000, result: '家庭信息修改成功！'};
                            } else {
                                return {success: false, result: '家庭信息修改失败！', resultCode: 1004};
                            }
                        } else {
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有填写注册信息！', resultCode: 1002};
                }
            }
        });
        // 删除家庭信息
        Api.addRoute('deleteFamily', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const fId = param.id;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token": logintoken});
                        if (user) {
                            const fams = Families.find({'createdUser._id': user._id}).count();
                            console.log('fams : ', fams);
                            if(fams == 1){
                                return {success: false, result: '这是所剩的唯一家庭，不能删除！', resultCode: 1004};
                            }else{
                                const fam = Families.findOne({_id: fId, 'createdUser._id': user._id});
                                if(fam){
                                    const family = Families.remove(fId);
                                    if (family) {
                                        Meteor.users.update({_id: user._id}, {$pull: { familyIds: fId }});
                                        const families = Families.find({'createdUser._id': user._id}).fetch();
                                        if(families.length > 0){
                                            Families.update({_id: families[0]._id}, {$set: {isDefault: true}});
                                        }
                                        return {success: true, result: '家庭信息删除成功！', resultCode: 1000};
                                    } else {
                                        return {success: false, result: '家庭信息删除失败！', resultCode: 1004};
                                    }
                                }else{
                                    return {success: false, result: '要删除的家庭不存在！', resultCode: 1004};
                                }

                            }
                        } else {
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有填写注册信息！', resultCode: 1002};
                }
            }
        });
        // 切换默认家庭信息
        Api.addRoute('changeDefaultFamily', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const fId = param.id;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token": logintoken});
                        if (user) {
                            const family = Families.update({_id: fId}, {$set: {isDefault: true}});
                            if (family) {
                                const fs = Families.find({'createdUser._id': user._id}).fetch();
                                fs.forEach((f) => {
                                    if(fId != f._id){
                                        Families.update({'_id': f._id}, {$set: {isDefault: false}});
                                    }
                                });
                                return {success: true, result: '默认家庭修改成功！', resultCode: 1000};
                            } else {
                                return {success: false, result: '默认家庭修改失败！', resultCode: 1004};
                            }
                        } else {
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有获取到信息！', resultCode: 1002};
                }
            }
        });
        // 添加房间
        Api.addRoute('addRoom', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const fId = param.id;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token": logintoken});
                        if (user) {
                            delete param.token;
                            delete param.id;
                            param['_id'] = Random.id();
                            const family = Families.update({_id: fId}, {$addToSet: {rooms: param}});
                                if (family) {
                                    return {success: true, result: '房间添加成功！', resultCode: 1000};
                                } else {
                                    return {success: false, result: '房间添加失败！', resultCode: 1004};
                                }

                        } else {
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有获取到信息！', resultCode: 1002};
                }
            }
        });
        // 编辑房间
        Api.addRoute('editRoom', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const rId = param.id;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token": logintoken});
                        if (user) {
                            const family = Families.findOne({'rooms._id': rId});
                            if (family) {
                                const rooms = family.rooms || [];
                                rooms.forEach((room) => {
                                    if(room._id == rId){
                                        if(param.name && param.name != ''){
                                            room['name'] = param.name
                                        }
                                        if(param.url && param.rul != '') {
                                            room['url'] = param.url
                                        }
                                    }
                                });
                                const f = Families.update({_id: family._id}, {$set: {rooms: rooms}});
                                if(f){
                                    return {success: true, result: '房间添加成功！', resultCode: 1000};
                                }else{
                                    return {success: false, result: '房间添加失败！', resultCode: 1004};
                                }

                            } else {
                                return {success: false, result: '没有找到要修改的房间！', resultCode: 1004};
                            }

                        } else {
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有获取到信息！', resultCode: 1002};
                }
            }
        });
        // 删除房间
        Api.addRoute('deleteRoom', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const rId = param.id;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token": logintoken});
                        if (user) {
                            const family = Families.findOne({'rooms._id': rId});
                            if (family) {
                                const rooms = family.rooms || [];
                                const arr = [];
                                rooms.forEach((room) => {
                                    if(room._id == rId && !room.isDef){
                                    }else{
                                        arr.push(room);
                                    }
                                })
                                const f = Families.update({_id: family._id}, {$set: {rooms: arr}});
                                if(f){
                                    return {success: true, result: '房间删除成功！', resultCode: 1000};
                                }else{
                                    return {success: false, result: '房间删除失败！', resultCode: 1004};
                                }

                            } else {
                                return {success: false, result: '没有找到要删除的房间！', resultCode: 1004};
                            }

                        } else {
                            return {success: false, result: '请登录！', resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有获取到信息！', resultCode: 1002};
                }
            }
        });
        // 房间列表
        Api.addRoute('getRooms', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const fId = param.id;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token": logintoken});
                        if (user) {
                            const family = Families.findOne({'_id': fId});
                            if (family) {
                                const rooms = family.rooms || [];
                                return {success: true, result: {rooms: rooms, error: ''}, resultCode: 1000};

                            } else {
                                return {success: false, result: {error: '请输入要查询的家庭ＩＤ！'} , resultCode: 1004};
                            }

                        } else {
                            return {success: false, result: {error: '请登录！'}, resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有获取到信息！', resultCode: 1002};
                }
            }
        });
        // 修改家庭的默认房间
        Api.addRoute('changeDefRooms', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const fId = param.id;
                        const rId = param.roomId;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token": logintoken});
                        if (user) {
                            const family = Families.findOne({'_id': fId});
                            if (family) {
                                const arr = family.rooms;
                                arr.forEach((r) => {
                                    if(r._id == rId){
                                        r.isDef = true;
                                    }else{
                                       if(r.isDef){
                                           r.isDef = false;
                                       }
                                    }
                                });
                                const f = Families.update({_id: family._id}, {$set: {rooms: arr}});
                                if(f){
                                    return {success: true, result: '默认房间修改成功！', resultCode: 1000};
                                }else{
                                    return {success: false, result: '默认房间修改失败！' , resultCode: 1004};
                                }
                            } else {
                                return {success: false, result: {error: '家庭信息不存在！'} , resultCode: 1004};
                            }

                        } else {
                            return {success: false, result: {error: '请登录！'}, resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有获取到信息！', resultCode: 1002};
                }
            }
        });
        // 房间详情
        Api.addRoute('getRoomInfo', {authRequired: false}, {
            post: {
                action() {
                    if (this.bodyParams) {
                        const param = this.bodyParams;
                        const logintoken = param.token;
                        const roomId = param.roomId;
                        const user = Meteor.users.findOne({"services.resume.loginTokens.token": logintoken});
                        if (user) {
                            const family = Families.findOne({'rooms._id': roomId});
                            if (family) {
                                const rooms = family.rooms || [];
                                const arr = R.filter((s) => {
                                        return s._id === roomId;
                                    })(rooms) || [];
                                return {success: true, result: {room: arr[0], error: ''}, resultCode: 1000};
                            } else {
                                return {success: false, result: {error: '请输入要查询的房间ＩＤ！'} , resultCode: 1004};
                            }

                        } else {
                            return {success: false, result: {error: '请登录！'}, resultCode: 1004};
                        }
                    }
                    return {success: false, result: '没有获取到信息！', resultCode: 1002};
                }
            }
        });
    });
}